/**
 * Created by Administrator on 2019/1/03
 */

(function ($) {
    const Message = function () {

        // 聊天面板 代码
        this.chat_panel = `
        <div class="person" data-chat="person{room_id}" data-room_id="{room_id}">
            <div class="user-info">
                <div class="f-head">
                    <img src="http://www.im.com/assets/backend/assets/img/90x90.jpg" alt="avatar">
                    <span class="badge badge-success"></span>
                </div>
                <div class="f-body">
                    <div class="meta-info">
                        <span class="user-name" data-name="{user_name}">{user_name}</span>
                        <span class="user-meta-time">{timer}</span>
                    </div>
                    <span class="preview">{user_name}正在咨询...</span>
                </div>
            </div>
        </div>
        `
        // 存放聊天消息的box
        this.msg_content = `
            <div class="chat" data-chat="person{room_id}" data-room_id="{room_id}">
                <div class="conversation-start">
                    <span>{timer}</span>
                </div>
            </div>
        `

        /**
         * 判断当前字符串是否为空值
         * @param {String} str  需要验证的字符串
         * @return {Boolean}
         * */
        this.isEmpty = function (str) {
            return !(typeof str === "undefined" || str === null || str === '');
        }
    }

    Message.prototype = {

        constructor: Message,

        /**
         * 用户上线处理
         * @param {Object} user_data
         * @param {Number} room_id
         * @param {Object} socket
         * */
        userOnline: function (user_data, room_id, socket) {

            if ($('.person[data-chat=person' + room_id + ']').length === 0) {
                let chat_panel = this.chat_panel.replace(/\{room_id\}/g, room_id)
                chat_panel = chat_panel.replace(/\{user_name\}/g, user_data.username)
                chat_panel = chat_panel.replace(/\{timer\}/g, user_data.online_time)
                $('.user-list-box .people').append(chat_panel)

                let msg_content = this.msg_content.replace(/\{room_id\}/g, room_id)
                msg_content = msg_content.replace(/\{timer\}/g, user_data.online_time)
                $('#chat-conversation-box-scroll').append(msg_content)
                // 绑定点击事件
                this.chatRoomSwitch()
                this.sendMsg(socket)

                if ($('.user-list-box .people .active').length === 0) {
                    // 判断是否有正在服务的客户 没有的话 默认当前
                    $('.person[data-chat=person' + room_id + ']').trigger('click')
                }
            } else {
                let badge = $('.person[data-chat=person' + room_id + ']').find('.badge')
                if (!badge.hasClass('badge-success')) {
                    badge.addClass('badge-success')
                }
                badge.removeClass('badge-dark')
            }
        },

        /**
         * 用户下线处理
         * @param {Number} room_id
         * */
        userLogoff: function (room_id) {
            let badge = $('.person[data-chat=person' + room_id + ']').find('.badge')
            if (!badge.hasClass('badge-dark')) {
                badge.addClass('badge-dark')
            }
            badge.removeClass('badge-success')
        },

        /**
         * 切换聊天对象
         * */
        chatRoomSwitch: function () {
            $('.user-list-box .person').on('click', function (event) {
                if ($(this).hasClass('.active')) {
                    return false
                } else {
                    var findChat = $(this).attr('data-chat')
                    var personName = $(this).find('.user-name').text()
                    var personImage = $(this).find('img').attr('src')
                    var hideTheNonSelectedContent = $(this).parents('.chat-system').find('.chat-box .chat-not-selected').hide()
                    var showChatInnerContent = $(this).parents('.chat-system').find('.chat-box .chat-box-inner').show()

                    if (window.innerWidth <= 767) {
                        $('.chat-box .current-chat-user-name .name').html(personName.split(' ')[0])
                    } else if (window.innerWidth > 767) {
                        $('.chat-box .current-chat-user-name .name').html(personName)
                    }
                    $('.chat-box .current-chat-user-name img').attr('src', personImage)
                    $('.chat').removeClass('active-chat')
                    $('.user-list-box .person').removeClass('active')
                    $('.chat-box .chat-box-inner').css('height', '100%');
                    $(this).addClass('active')
                    $('.chat[data-chat = ' + findChat + ']').addClass('active-chat')
                }

                if ($(this).parents('.user-list-box').hasClass('user-list-box-show')) {
                    $(this).parents('.user-list-box').removeClass('user-list-box-show')
                }

                $('.chat-meta-user').addClass('chat-active')
                $('.chat-box').css('height', 'calc(100vh - 232px)')
                $('.chat-footer').addClass('chat-active')

                const ps = new PerfectScrollbar('.chat-conversation-box', {
                    suppressScrollX: true
                });

                const getScrollContainer = document.querySelector('.chat-conversation-box')
                getScrollContainer.scrollTop = 0
            });
        },

        /**
         * 发送消息
         * @param {Object} socket
         * */
        sendMsg: function (socket) {
            let _this = this

            $('.mail-write-box').on('keydown', function (event) {

                if (event.key === 'Enter') {

                    let room_id = $('.user-list-box .people').find('.active').data('room_id')

                    let chatInput = $(this)
                    let chatMessageValue = chatInput.val()
                    if (chatMessageValue === '') {
                        return false
                    }
                    _this.getMsgHtml('me', chatMessageValue)
                    chatInput.val('')

                    let msg_data = {
                        room_id: room_id,
                        user_type: window.user_type,
                        data: {
                            'message': chatMessageValue
                        }
                    }
                    socket.send(JSON.stringify(msg_data))
                }
            })
        },

        /**
         * 接收消息
         * @param {String} msg
         * */
        receiveMsg: function (msg) {
            this.getMsgHtml('you', msg)
        },

        /**
         * 获取消息html
         * @param {String} type
         * @param {String} message
         * */
        getMsgHtml: function (type, message) {
            let messageHtml = '<div class="bubble ' + type + '">' + message + '</div>'
            $('#chat-conversation-box-scroll .active-chat').append(messageHtml)
            const getScrollContainer = document.querySelector('.chat-conversation-box')
            getScrollContainer.scrollTop = getScrollContainer.scrollHeight
        },

        /**
         * sweet 定时关闭弹窗
         * */
        sweetTimer: function () {
            // 请求地址
            let content  = arguments[0]
            if (typeof content !== 'string' || !this.isEmpty(content)) {
                throw '请输入正确提示内容'
            }
            // 请求数据
            let timer = arguments[1]
            if (typeof timer !== 'number' || parseInt(timer) <= 0) {
                timer = 2000
            }
            // 请求成功回调
            let callback       = arguments[2]

            swal({
                title: content,
                text: '弹窗将在' + timer / 1000 + '秒后自动关闭',
                timer: timer,
                padding: '2em',
                onOpen: function () {
                    swal.showLoading()
                }
            }).then(function (result) {
                if (
                    // Read more about handling dismissals
                    result.dismiss === swal.DismissReason.timer
                ) {
                    if (typeof callback === 'function') {
                        callback()
                    }
                }
            })
        },

        /**
         * sweet成功失败 提示
         * */
        sweetTips: function () {
            swal({
                title: 'Good job!',
                text: "You clicked the!",
                type: 'error',
                padding: '2em'
            })
        }
    }

    window.Message = new Message()

})(jQuery)

const ps = new PerfectScrollbar('.people', {
    suppressScrollX: true
})

Message.chatRoomSwitch()
